<template>
  <div v-loading="loading">
    <!-- 未开通 start -->
    <div v-if="list.length===0" class="empty-container app-main-content-box">
      <div class="img">
        <img src="@/assets/icon/i-no-auth.png" alt>
      </div>
      <div class="msg">商城还未入驻店铺，快去入驻第一家店铺吧</div>
      <el-button type="primary" size="small" round @click="addStore">入驻店铺</el-button>
    </div>
    <!-- 未开通 end -->

    <!-- 已开通 start-->
    <div v-else class="shop-container">
      <!-- left 列表 -->
      <div class="left-container">
        <div class="menu-box">
          <div class="filter">
            <!-- <div class="title">店铺列表</div> -->
            <el-input v-model="filterVal" placeholder="请输入名称搜索" size="small" />
          </div>
          <div class="content">
            <el-button
              type="text"
              size="small"
              round
              icon="el-icon-plus"
              class="add-btn"
              @click="addStore"
            >入驻新店铺</el-button>
            <div
              v-for="item in list"
              :key="item.storeId"
              :class="[item.storeId===activeStore.storeId?'active':'']"
              class="item"
              :title="'id:'+item.storeId"
              @click="clickMenu(item)"
            >
              {{ item.name }}
              <span v-if="item.disabled" class="app-text-color-danger">(已关停)</span>
            </div>
          </div>
        </div>
      </div>

      <!--  right 配置 -->
      <div class="right-container app-main-content-box">
        <div class="right-head flexRBC">
          <div class="flexRSC">
            <div class="shop-name">{{ activeStore.name }}</div>
            <div>
              <el-tag v-if="activeStore.disabled" type="danger" size="small" round>已关停</el-tag>
              <el-tag v-else type="primary" size="small" round>启用中</el-tag>
              <el-tag
                v-if="!activeStore.disabled&&activeStore.status==1"
                type="success"
                size="small"
                round
              >正常营业</el-tag>
              <el-tag
                v-if="!activeStore.disabled&&activeStore.status==0"
                type="info"
                size="small"
                round
              >已打烊</el-tag>
            </div>
          </div>
          <div>
            <el-button
              v-if="activeStore.disabled"
              type="primary"
              round
              size="small"
              @click="updateStatus({disabled:false})"
            >启用店铺</el-button>
            <el-button
              v-else
              type="danger"
              round
              size="small"
              @click="updateStatus({disabled:true})"
            >关停店铺</el-button>
            <el-button
              v-if="!activeStore.disabled&&activeStore.status==1"
              type="info"
              round
              size="small"
              @click="updateStatus({status:0})"
            >打烊</el-button>
            <el-button
              v-if="!activeStore.disabled&&activeStore.status==0"
              type="success"
              round
              size="small"
              @click="updateStatus({status:1})"
            >营业</el-button>
          </div>
        </div>
        <div>
          <el-form
            ref="form"
            v-loading="loading"
            :model="form"
            :rules="rules"
            size="small"
            label-width="100px"
          >
            <el-form-item label="店铺服务：" prop="supportList">
              <el-select v-model="form.supportList" value-key="id" multiple placeholder="请选择">
                <el-option
                  v-for="item in supportOptions"
                  :key="item.id"
                  :label="item.title"
                  :value="item"
                />
              </el-select>
            </el-form-item>
            <!--            <el-form-item label="支付方式：" prop="payChannels">-->
            <!--              <el-checkbox-group v-model="form.payChannels">-->
            <!--                <el-checkbox-->
            <!--                  v-for="item in paymentOptions"-->
            <!--                  :key="item.key"-->
            <!--                  :label="item.key"-->
            <!--                >{{ item.label }}</el-checkbox>-->
            <!--              </el-checkbox-group>-->
            <!--            </el-form-item>-->
            <!--            <el-form-item label="店铺图片：" prop="imageList">-->
            <!--              <div class="img-list-container">-->
            <!--                <draggable :list="form.imageList" :options="{ filter: '.undrag' }">-->
            <!--                  <div v-for="(v, i) in form.imageList" :key="i" class="img-item drag">-->
            <!--                    <img :src="v.url" alt>-->
            <!--                    <div class="handle-icon">-->
            <!--                      <i class="el-icon-zoom-in icon" @click="handlePreview(v)" />-->
            <!--                      <i class="el-icon-delete icon" @click="handleImgRemove(v, i)" />-->
            <!--                    </div>-->
            <!--                  </div>-->

            <!--                  <div class="img-item undrag">-->
            <!--                    <el-upload-->
            <!--                      :limit="10"-->
            <!--                      :action="actionUrl"-->
            <!--                      :headers="{ 'X-BUSINESS-TOKEN': $store.state.user.token }"-->
            <!--                      :file-list="form.imageList"-->
            <!--                      :before-upload="handleImgBefore"-->
            <!--                      :on-success="handleImgSuccess"-->
            <!--                      :on-exceed="handleImgExceed"-->
            <!--                      drag-->
            <!--                      multiple-->
            <!--                      :show-file-list="false"-->
            <!--                      list-type="picture-card"-->
            <!--                      class="upload-container"-->
            <!--                    >-->
            <!--                      <i class="el-icon-upload" />-->
            <!--                      <div class="el-upload__text">-->
            <!--                        将文件拖到此处，或-->
            <!--                        <em>点击上传</em>-->
            <!--                      </div>-->
            <!--                    </el-upload>-->
            <!--                    <el-dialog title="图片预览" :visible.sync="dialogImageVisible">-->
            <!--                      <img width="100%" :src="dialogImageUrl" alt>-->
            <!--                    </el-dialog>-->
            <!--                  </div>-->
            <!--                </draggable>-->
            <!--              </div>-->
            <!--              <div class="upload-tips">-->
            <!--                <div>1.只能上传jpg/png文件，且不超过1mb</div>-->
            <!--                <div>2.建议尺寸1060*530像素，最多上传10张</div>-->
            <!--                <div>3.可长按图片进行拖拽排序</div>-->
            <!--              </div>-->
            <!--            </el-form-item>-->
            <!--            <el-form-item label="店铺描述：" prop="description">-->
            <!--              <el-input-->
            <!--                v-model="form.description"-->
            <!--                type="textarea"-->
            <!--                :autosize="{ minRows: 2, maxRows: 6}"-->
            <!--                maxlength="200"-->
            <!--                show-word-limit-->
            <!--              />-->
            <!--            </el-form-item>-->
            <el-form-item>
              <el-button type="primary" round @click="submit">保存配置</el-button>
              <el-button round @click="reset">重置配置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <!-- 已开通 end-->

    <!-- 组件 -->
    <DialogAddShop ref="dialogAddShop" />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  storeList,
  storeDetail,
  updateStore,
  updateStoreStatus
} from '@/views/wxaMallModule/api/shop'
import { supportList } from '@/views/wxaMallModule/api/support'
import { imgUploadUrl } from '@/api/upload'
import DialogAddShop from './DialogAddShop/index'
import draggable from 'vuedraggable'
export default {
  components: {
    draggable,
    DialogAddShop
  },
  data() {
    return {
      // 校验规则
      rules: {
        // payChannels: {
        //   type: 'array',
        //   required: true,
        //   message: '请至少选择一种支付方式',
        //   trigger: ['change']
        // },
        // imageList: {
        //   type: 'array',
        //   required: true,
        //   message: '请上传店铺图片',
        //   trigger: ['change']
        // }
      },
      // 配置
      supportOptions: [],
      paymentOptions: [
        {
          key: 'WX',
          label: '微信支付'
        },
        { key: 'BALANCE', label: '会员钱包' }
      ],
      actionUrl: imgUploadUrl,
      // 状态
      loading: false,
      dialogImageVisible: false,
      // 数据
      dialogImageUrl: '',
      filterVal: '',
      activeStore: {
        storeId: null
      },
      list: [],
      form: {
        supportList: [],
        payChannels: [],
        imageList: [],
        address: '',
        area: '',
        city: '',
        description: '',
        latitude: 0,
        longitude: 0,
        name: '',
        phone: '',
        province: '',
        shopId: 0,
        storeId: 0
      }
    }
  },
  computed: {
    ...mapGetters(['fileBaseUrl'])
  },
  watch: {
    'activeStore.storeId'(val) {
      if (val) {
        this.getDetail(val)
      }
    }
  },
  created() {},
  mounted() {
    // 获取数据
    this.fetchData()
  },
  methods: {
    /**
       * 数据组
       */
    // 获取数据
    fetchData() {
      this.loading = true
      Promise.all([this.getShopList(), this.getSupportOptions()])
        .then(() => {})
        .finally(() => {
          this.loading = false
        })
    },

    // 获取门店列表
    getShopList(mode = null) {
      return new Promise((resolve, reject) => {
        storeList()
          .then((res) => {
            this.list = res.data
            if (res.data.length > 0) {
              if (mode === 'add') {
                this.activeStore = res.data[res.data.length - 1]
              } else if (!this.storeId) {
                this.activeStore = res.data[0]
              }
            }
          })
          .catch(() => {})
          .finally(() => {
            resolve()
          })
      })
    },

    // 获取服务列表
    getSupportOptions() {
      return new Promise((resolve, reject) => {
        supportList({ type: 0 })
          .then((res) => {
            this.supportOptions = res.data
          })
          .finally(() => {
            resolve()
          })
      })
    },

    // 获取详情
    getDetail(storeId) {
      this.loading = true
      storeDetail({ storeId })
        .then((res) => {
          res.data.imageList = res.data.imageList.map((v) => {
            return {
              response: { code: 0, data: { path: v } },
              url: this.fileBaseUrl + v
            }
          })
          this.form = res.data
          this.$nextTick(() => {
            this.$refs.form.clearValidate()
          })
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false
        })
    },

    /**
       * 按钮组
       */
    // 开通店铺
    addStore() {
      const selectShopIds = []
      this.list.forEach((v) => {
        selectShopIds.push(v.shopId)
      })
      this.$refs.dialogAddShop.open({ selectShopIds }).then((res) => {
        this.getShopList('add')
      })
    },

    // 选择门店
    clickMenu(item) {
      this.activeStore = item
    },

    // 保存表单
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const params = JSON.parse(JSON.stringify(this.form))
          params.imageList = params.imageList.map((v) => {
            if (
              v.response &&
                v.response.code === 0 &&
                v.response.data &&
                v.response.data.path
            ) {
              return v.response.data.path
            }
          })
          this.loading = true
          updateStore(params)
            .then((res) => {
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000,
                offset: 40
              })
            })
            .catch(() => {})
            .finally(() => {
              this.loading = false
            })
        }
      })
    },

    // 重置表单
    reset() {
      if (this.activeStore.storeId) {
        this.getDetail(this.activeStore.storeId)
      }
    },

    // 关停 打烊门店
    updateStatus(params) {
      let typeText = ''
      if (Object.prototype.hasOwnProperty.call(params, 'disabled')) {
        typeText = params.disabled ? '停用' : '启用'
      }
      if (Object.prototype.hasOwnProperty.call(params, 'status')) {
        typeText = params.status ? '营业' : '打烊'
      }
      this.$confirm(
        `您确定${typeText}门店：${this.activeStore.name}?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true,
          roundButton: true
        }
      )
        .then(() => {
          this.loading = true
          params.storeId = this.form.storeId
          updateStoreStatus(params)
            .then(() => {
              if (Object.prototype.hasOwnProperty.call(params, 'disabled')) { this.activeStore.disabled = params.disabled }
              if (Object.prototype.hasOwnProperty.call(params, 'status')) { this.activeStore.status = params.status }
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000,
                offset: 40
              })
            })
            .catch(() => {})
            .finally(() => {
              this.loading = false
            })
        })
        .catch(() => {})
    },

    // 上传图片
    handleImgBefore(file) {
      return this.beforeUploadImg(file, this, 0, 0, 1)
    },

    handleImgSuccess(res, file, fileList) {
      if (res.code === 0) {
        this.form.imageList = fileList
        this.$refs.form.clearValidate(['imageList'])
      } else {
        this.$message.error(res.msg)
      }
    },

    handleImgRemove(v, i) {
      this.form.imageList.splice(i, 1)
    },

    handlePreview(file) {
      this.dialogImageUrl = file.url
      this.dialogImageVisible = true
    },

    handleImgExceed() {
      this.$message.error('最多上传10张')
    }

    /**
       * 状态组
       */

    /**
       * 方法组
       */
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  /* 未开通 */
  .empty-container {
    padding: 50px 0;
    text-align: center;
    .img {
      margin: 0 auto;
      width: 307px;
      height: 278px;
    }
    .msg {
      height: 50px;
      line-height: 50px;
      font-size: 16px;
    }
  }

  /* 门店 */
  .shop-container {
    display: flex;
    .left-container {
      flex: 0 0 200px;
    }
    .right-container {
      flex: 1;
      .right-head {
        margin-bottom: 20px;
        .shop-name {
          margin-right: 10px;
          font-size: 20px;
          font-weight: bold;
        }
      }
      .el-textarea,
      .el-select {
        width: 500px;
      }
    }
  }

  /* 门店列表 */
  .menu-box {
    margin-right: 10px;
    background-color: #fff;
    border-radius: 5px;
    min-height: 500px;
    .filter {
      padding: 10px;
    }
    .content {
      font-size: 14px;
      .add-btn {
        width: 100%;
      }
      .item {
        cursor: pointer;
        padding: 10px;
        width: 100%;
      }
      .active {
        color: #fff;
        background-color: $primary;
      }
    }
  }

  /* 上传 */
  .img-list-container {
    margin: 0;
    display: inline;
    vertical-align: top;
    cursor: pointer;
    .img-item {
      position: relative;
      overflow: hidden;
      background-color: #fff;
      border: 1px solid #c0ccda;
      border-radius: 6px;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      height: 150px;
      width: 300px;
      margin: 0 8px 8px 0;
      display: inline-block;
      .handle-icon {
        display: none;
      }
      &:hover {
        font-size: 20px;
        color: #fff;
        .handle-icon {
          display: block;
          position: absolute;
          top: 0;
          left: 0;
          display: flex;
          align-items: center;
          justify-content: center;
          width: 100%;
          height: 100%;
          background-color: rgba(0, 0, 0, 0.5);
          .icon {
            margin: 10px;
          }
        }
      }
    }
  }
  .upload-container ::v-deep {
    .el-upload-dragger {
      width: 298px;
      height: 148px;
    }
    .el-upload--picture-card {
      line-height: 1;
      width: 300px;
      height: 150px;
      border: none;
    }
    .el-upload-list__item {
      width: 300px;
      height: 150px;
    }
  }
</style>
